#include "DCreature.h"
#include "../GlobalGameData.h"

using namespace DeepClasses;


DeepClasses::DCreature::DCreature(DString name, wchar_t code, short color) 
: DObject(name,code,color)
{
	m_task = new DTskIdle();
	m_state.hunger=DCR_HUNGER_INIT;
	m_properties.hunger_max=DCR_HUNGER_MAX;
	m_properties.hunger_per_tick=DCR_HUNGER_PER_TICK;
	
}

DeepClasses::DCreature::~DCreature()
{
	ClearTasks();
	if(m_task!=NULL)
		delete m_task;
	m_task=NULL;
}

int DeepClasses::DCreature::Tick()
{
	DObject::Tick();
	m_state.hunger-=m_properties.hunger_per_tick;

	return DE_OK;
}

int DeepClasses::DCreature::InsertTask( DTask* tsk )
{
	tsk->m_next=m_task;
	tsk->m_owner=this;
	m_task=tsk;
	return DE_OK;
}

int DeepClasses::DCreature::ClearTasks()
{
	// delete all tasks in chain except one last task
	// last task should be DTASKS_Idle. If not - replace it.
	while(m_task!=NULL)
	{
		if(m_task->m_next==NULL)
		{
			if(m_task->m_curTask==DTASK_idle)
				break;
			else
			{
				delete m_task;
				m_task = new DTskIdle();
			}
		}
		else
		{
			DTask* tmp = m_task;
			m_task = m_task->m_next;
			delete tmp;
		}
	}
	return DE_OK;
}

int DeepClasses::DCreature::Move( TLocation newLoc )
{
	DCell* oldCell = gameData.m_world->m_map.GetCellAt(m_pos);	
	DCell* newCell = gameData.m_world->m_map.GetCellAt(newLoc);
	oldCell->m_creature=newCell->m_creature;
	newCell->m_creature=this;
	m_pos=newLoc;
	return DE_OK;
}

int DeepClasses::DCreature::Place( TLocation loc )
{
	DCell* newCell = gameData.m_world->m_map.GetCellAt(loc);
	newCell->m_creature=this;
	m_pos=loc;
	InsertTask(new DTskIdle());
	return DE_OK;
}

DeepClasses::DDwarf::DDwarf(DString name, wchar_t code, short color)
: DCreature(name,code,color)
{

}

DeepClasses::DDwarf::~DDwarf()
{

}

int DeepClasses::DDwarf::Tick()
{
	DCreature::Tick();

	m_task->Tick();

	return DE_OK;
}
